<style rel="stylesheet/scss" lang="scss" scoped>
	.new-pro-table {
		width: 100%;
		display: flex;
		flex: 1;
		flex-direction: column;
		margin-top: 10px;
		position: relative;
		border: 1px solid #E5E5E5;
		.tab-creen {
			width: 100%;
			height: 50px;
			display: flex;
			padding: 0 10px;
			font-size: 14px;
			box-sizing: border-box;
			align-items: center;
		}
		.tab-con {
			flex: 1;
			overflow: auto;
			height: auto;
			position: relative;
			.sc-box {
				min-width: 100%;
				height: 50px;
				display: flex;
				padding: 0 10px;
				align-items: center;
				background: #fff;
				border: 1px solid #ebeef5;
				padding-left: 55px;
			}
		}
		.box-flex {
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.sp-w-50{
			width: 100px;
			display: block;
		}
		.tab-page {
			width: 100%;
			height: 40px;
			display: flex;
			justify-content: center;
			align-items: center;
			border-top: 1px solid #E5E5E5;
		}
		.area-box {
			resize: none;
			display: block;
			width: 100%;
			padding: 10px;
			height: 300px;
		}
		.el-table{
			min-width: 100%;
		}
		.sp-name{
			display: inline-block;
			width: 100px;
		}
		.w-input_10{
			width: 200px;
		}
	}
</style>
<template>
	<div class="new-pro-table" v-loading.fullscreen.lock="fullscreenLoading">
		<div class="tab-creen">
			<span class="m-r-10">|已选车型</span>
			<el-button type="primary" size="mini" @click="setTableHead">设置表头{{modelList.length}}</el-button>
			<el-button type="primary" size="mini" @click="setAttribute">设置属性值</el-button>
		</div>
		<div class="tab-con" :style="'width:' + clWidth + 'px'">
			<!-- <div class="sc-box" :style="'width:' + cheList.length*83 + 'px'" v-if="modelList.length>0">
				<screening @handleInput="handleInput" @filterListFn="filterListFn" :flag="item.showDrep" :head-tit-list="headTitList" @hideDrep="hideDrep"
				    ref="screen" :step="index" v-for="(item, index) in cheList">
				</screening>
			</div> -->
			
			<el-table 
				:style="'width:' + cheList.length*83 + 'px'"  
				ref="multipleTable" :data="modelList" 
				highlight-current-row :fit='false'
				class="el-table"
			    @selection-change="handleSelectionChanges" size="mini">
				<el-table-column type="selection" width="50px" align="center" fixed="left"></el-table-column>
				<el-table-column v-for="tableHeader in modelHead" :label="tableHeader.showName" align="center" width="200px">
					<template slot-scope="scope">
						<div style='width:100%:height:100%;text-align: center;'>
							
							<span>{{scope.row[tableHeader.keyId].text }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column fixed="right" label="操作" align="left" width="100" v-if="proStep && modelList.length>=6">
					<template slot-scope="scope">
						<el-button @click="handleClick(scope.row)" type="text" size="small" style="color: red;">删除</el-button>
					</template>
				</el-table-column>
				<el-table-column fixed="right" label="操作" align="left" width="110" v-else>
					<template slot-scope="scope">
						<el-button @click="handleClick(scope.row)" type="text" size="small" style="color: red;">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<div class="tab-page">
			 <el-checkbox v-model="checkedVal" @change="setSelectList">全选</el-checkbox>
			 <el-button type="danger" size="mini" class="m-l-10" @click="handleClick(1)">
				 取消关联{{totalNum > 0 ? totalNum  : selectTabList.length > 0 ? selectTabList.length : 0}}个车型
			 </el-button>
			<current-page :current-page="f_page" :page-size="f_PageSize" :page-total="f_total" @handleCurrentChange="handleTabChange"></current-page>
		</div>
		<!--设置表头-->
		<el-dialog title="设置属性" center :visible.sync="passDialog" width="30%">
            <el-row class="p-all-20 ">
                <el-col :span="100" class="box-flex m-b-10">
                    <span class="sp-name m-r-10">属性名称:</span>
                    <el-select v-model="groupName" placeholder="请选择" class="w-input_10" @change="setGroupName">
                        <el-option v-for="item in groupList"  :label="item.showName" :value="item.showName">
                        </el-option>
                    </el-select>
                </el-col>
            </el-row>

            <el-row class="p-all-20 ">
                <el-col :span="100" class="box-flex m-b-10">
                    <span class="sp-name m-r-10">属性值:</span>
                    <el-input v-model="groupValue" class="w-input_10" maxlength="20"/>
                </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button @click="passDialog = false">取 消</el-button>
                <el-button type="primary" @click="saveAdmin">确 定</el-button>
            </span>
        </el-dialog>
	</div>
</template>
<script>
	import {
		mapMutations,
		mapGetters
	} from 'vuex'
	import {
		SUCCESS_REQUEST_STATUS
	} from '@/utils/config.js'
	import {
		getToken
	} from '@/utils/auth'
	import currentPage from '@/components/current-page/current-page.vue'
	import screening from '../../components/screening.vue'
	export default {
		props: {
			proStep: {
				type: Boolean,
				default : false,
			},
			// 商品id
			goodsId: {
				type: String,
				default : '',
			},
			// 二级分类id
			secCatId: {
				type: String,
				default : '',
			}
		},
		data() {
			return {
				f_page: 0,
				f_PageSize: 20,
				f_total: 0,
				modelIds: '',
				modelHead: [],
				brandValue: '',
				cheList: [],
				load: false,
				num: 0,
				clWidth: 0,
				totalNum:0,
				groupName: '',
				catId: 'CAT5a436f18db573c07a291ee16',
				selList: [],
				modelList: [],
				headTitList: [],
				branOptions: [],
				modelValue: '',
				groupValue: '',
				groupList: [],
				checkedVal: false,
				selectTabList: [],
				passDialog: false,
				centerDialogVisible: false,
				fullscreenLoading: false
			}
		},
		created() {
			this._initProList()
			this._initProHead()
		},
		mounted() {
			let _this = this
			document.onclick = function () {
				let e = e || window.event
				let el = e.srcElement.className
				if (el !== 'he-input' && el !== 'item-li' && el !== 'item-ul' && el != 'el-checkbox__label' && el !=
					'el-checkbox__original' && el != 'load-more' && el != 'el-checkbox__inner') {
					_this.cheList.forEach((item) => {
						item.showDrep = false
					})
					return
				}
			}
			this.clWidth = document.getElementById('good-containter').clientWidth
		},
		methods: {
			setGroupName(val) {
				console.log(val)
				console.log(this.groupList)
			},
			// 设置属性值
			setAttribute() {
				console.log(this.selectTabList)
				if(!this.selectTabList.length) {
					this.$message({
						type:'error',
						message: '请先勾选所要修改车型'
					})
					return
				}
                //设置属性值
                this.$ajax({
                    api: 'merchant/getNewHeadList',
					params: {
						token: getToken(),
						catId: this.getStepCache.secondCartId,
						merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') : '',
					}
                }).then(res => {
					console.log(res)

                    if (res.status === 200) {
                        this.groupList = res.data
						this.passDialog = true
                    }else{
						this.$message({
							type: 'error',
							message: res.data.message
						})
					}
                }).catch(err => {
                    this.$message({
                        type: 'error',
                        message: err.message
                    })
                })
			},
			saveAdmin() {
				//groupName
				let attr = this.groupList.filter((item) => {return item.showName == this.groupName})
				console.log(attr)
				if(!this.groupValue){
					this.$message({
						type:'error',
						message: '属性值不能为空'
					})
					return
				}
				this.$ajax({
					api: 'merchant/modelproperty/save',
					params: {
						keyId: attr[0].keyId,
						modelIds: this.selectTabList.join(','),
						text: this.groupValue,
						token: getToken(),
						catId: this.getStepCache.secondCartId,
						merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') : '',
					}
				}).then(res => {
					if(res.status === 200) {
						this.$message({
							type:'success',
							message: '设置成功'
						})
						this.passDialog = false
						this._initProList()
					}
				})
			},
			// 设置表头
			setTableHead() {
				this.$emit('setTableHead')
			},
			// 全选
			setSelectList () {
				if(this.f_total ) {
					this.totalNum = this.checkedVal ? this.f_total	 : 0
					this.selectTabList = []
					this.modelList.forEach((item, index) => {
						this.$refs.multipleTable.toggleRowSelection(item, false);
						
					})
				}else if(this.f_total){
					if(this.checkedVal) {
						this.modelList.forEach((item, index) => {
							this.$refs.multipleTable.toggleRowSelection(item, true);
							this.selectTabList.push(item)
						})
						this.$refs.multipleTable.toggleRowSelection(2, true);
						return
					}else{
						this.modelList.forEach((item, index) => {
							this.$refs.multipleTable.toggleRowSelection(item, false);
							this.selectTabList.push(item)
						})
						this.$refs.multipleTable.toggleRowSelection(2, false);
					}
					this.selectTabList = []
				}
			},
			// 删除商品匹配车型
			handleClick(item) {
				console.log(item)
				let carIds = ''
				if(item != 1 ){
					
					for(let i in item) {
						if(!carIds) {
							carIds = item[i].modelId
						}
					}
				}else{
					if(!this.selectTabList.length && !this.totalNum) {
						this.$message({
							type:'error',
							message: '请选择取消关联的车型'
						})
						return
					}
					if(!this.totalNum) {
						carIds = this.selectTabList.join(',')
					}
				}
				if(carIds || this.totalNum) {
					this.fullscreenLoading = true
					this.$ajax({
						api: 'goods/car/linkdelete1',
						params: {
							token: getToken(),
							goodsId: this.getStepCache.goodId,
							carIds: carIds ? carIds:'',
							gcId: this.getStepCache.gcId ? this.getStepCache.gcId: '',
							merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') : '',
						}
					}).then(res => {
						console.log(res)
						if(res.status === SUCCESS_REQUEST_STATUS) {
							this.$message({
								type:'success',
								message: '取消关联成功'
							})
							this.checkedVal = false
							this._initProList()
						}
					})
				}
			},
			searchList() {
				if (this.modelIds) {
					this._initProList()
					this.centerDialogVisible = false
				}
			},
			// 输入车型id
			textareaInput() {
				let ids = []
				ids = this.getModelIds()
				this.modelIds = ids
			},
			getModelIds() {
				let texts = [];
				texts = this.modelValue.split("\n");
				for (var i = 0; i < texts.length; i++) {
					let id = 0
					try {
						id = Number.parseInt(texts[i].trim());
					} catch (error) {}
					if (Number.isNaN(id)) {
						texts.splice(i, 1);
					} else {
						i++;
					}
				}
				return texts;
			},
			initCheList() {
				this.modelHead.forEach((item) => {
					let obj = {
						showDrep: false
					}
					this.cheList.push(obj)
				})
			},
			// 选中
			handleSelectionChanges(val) {
				this.selectTabList = val
				console.log(val)
				let valueId = ''
				let attr = []
				 val.forEach((item) => {
					for (let i in item) {
						attr.push(item[i].modelId)
					}
				})
				attr = new Set(attr)
				let newArr = Array.from(attr) // 再把set转变成array
				console.log(newArr)
				this.selectTabList = newArr
				this.selectTabList.forEach((item,index) => {
					if(item == undefined) {
						this.selectTabList.splice(index, 1)
					}
				})
				this.selList = this.selectTabList
				setTimeout(() =>{
					if(this.selectTabList.length>0){
						this.totalNum = 0
						this.checkedVal = false
					}
				},200)
				
			},
			_initProList(obj) {
				let defaultpra = {
					page: this.f_page,
					pageSize: 20,
					catId: this.getStepCache.secondCartId,
					goodsId: this.getStepCache.goodId,
					gcId: this.getStepCache.gcId,
					token: getToken(),
					modelIds: this.modelIds,
					merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') : '',
				}
				this.fullscreenLoading = true
				let param = Object.assign({}, defaultpra, obj, this.keyObj)
				this.$ajax({
					api: 'goods/car/linkquery1',
					params: param
				}).then((res) => {
					console.log(res)
					this.fullscreenLoading = false
					if (res.status === 200) {
						console.log(888)
						console.log(res.data.modelList)
						this.modelList = res.data.modelList
						let attrObj = Object.assign({}, this.getStepCache,{gcId: res.data.gcId ? res.data.gcId : ''})
						this.setStepCache(attrObj)
						console.log(this.getStepCache)
						this.f_total = res.data.page.total
						this.checkedVal = true
						this.totalNum =  this.f_total
					}
				})
			},
			_initProHead() {
				this.$ajax({
					api: 'merchant/modelhead',
					params: {
						token: getToken(),
						catId: this.getStepCache.secondCartId,
						merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') :
							'',
						showSelected: true
					}
				}).then(res => {
					console.log(res)
					if (res.status === 200) {
						this.modelHead = res.data
						this.initCheList()
						this.load = true
					}
				})
			},
			// 触发点击页码
			handleTabChange(val) {
				this.f_page = val
				this.fullscreenLoading = true
				this._initProList()
			},
			// 搜索得到焦点
			handleInput(val) {
				this.getModelheadoption(val, this.modelHead[this.num].keyId)
			},
			filterListFn() {
				let value = this.headTitList.filter((item) => {
					return item.select
				}).map((i) => {
					return i.value
				})
				this.keyObj = {
					[this.keyId]: value.join(',')
				}
				this._initProList()
			},
			getModelheadoption(text = '', keyId) {
				this.keyId = keyId
				this.$ajax({
					api: 'modelheadoption',
					params: {
						keyId: keyId,
						text: text
					}
				}).then(res => {
					this.fullscreenLoading1 = false
					if (res.status === 200) {
						res.data.forEach((item) => {
							item.select = false
						})
						this.headTitList = res.data
					}
					this.time = null
				})
			},
			hideDrep(num) {
				this.cheList.forEach((item) => {
					item.showDrep = false
				})
				this.headTitList = []
				this.num = num
				this.fullscreenLoading1 = true
				this.cheList[num].showDrep = true
				if (this.cheList[num].showDrep) {
					console.log(this.modelHead[num])
					this.getModelheadoption('', this.modelHead[num].keyId)
				}

			},
			...mapMutations({
				setStepCache: 'SET_STEP_CACHE',
			})
		},
		watch: {
			modelList(val) {
				console.log('长度'+val.length)
				this.$emit('modelFlag',val.length> 0? false : true )
			}
		},
		components: {
			screening,
			currentPage
		},
		computed: {
			...mapGetters([
				'getStepCache'
			])
		}
	}
</script>
